import { last, merge, pick } from 'lodash-es'

import { appMapping, BaseAppName } from '@/settings'
import { appStore } from '@/store/modules/app'
import { getAppInfo } from '@/utils'

interface ExtraData {
  appId?: string
  baseAppId?: string
  apiUrl?: string
  appCode?: string
  [k: string]: any
}

export function getAppNameByRoute() {
  const { route } = last(getCurrentPages()) as unknown as Page.PageInstance
  const [, appName] = /^(?:apps|pages)\/([\w-]+)\//.exec(route as string) || []
  return appName ?? BaseAppName
}

export function getCurrentExtraData(): ExtraData {
  const appName = getAppNameByRoute()
  const { appCode, extraData } = appMapping[appName] ?? appMapping[BaseAppName]

  const appInfo = getAppInfo(appCode)
  appInfo && appStore.setCurrentAppInfo(appInfo)

  if (!appInfo) {
    console.warn(
      `AppName: ${appName} AppCode: ${
        Array.isArray(appCode) ? appCode.join() : appCode
      }；未找到对应的应用信息！`
    )
  }
  return merge(
    pick(appInfo, 'appId', 'baseAppId', 'apiUrl', 'appCode'),
    extraData
  )
}
